<template>
  <!-- 🔧 已修复contract_workflow参数问题 - 2025-11-13 🔧 -->
  <div class="drawer-content-wrapper">
    <el-form
      ref="formRef"
      :model="contractForm"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="form-section-title">基本信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同名称" prop="name">
                <el-input v-model="contractForm.name" placeholder="请输入合同名称"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="合同编号" prop="code">
                <el-input v-model="contractForm.code" placeholder="请输入合同编号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="签约主体(乙方)" prop="subject_id">
                <el-select
                  v-model="contractForm.subject_id"
                  placeholder="请选择签约主体公司"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in enterpriseList"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="合同类别" prop="cate_id">
                <el-select
                  v-model="contractForm.cate_id"
                  placeholder="请选择合同类别"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in contractCategories"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="客户名称(甲方)" prop="customer">
                <el-input v-model="contractForm.customer" placeholder="请输入客户名称">
                  <template #append>
                    <el-button @click="selectCustomer">选择</el-button>
                  </template>
                </el-input>
                <input type="hidden" v-model="contractForm.customer_id" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户代表" prop="contact_name">
                <el-input
                  v-model="contractForm.contact_name"
                  placeholder="请输入客户代表姓名"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="客户联系电话">
                <el-input
                  v-model="contractForm.contact_mobile"
                  placeholder="请输入客户联系电话"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同金额" prop="cost">
                <el-input v-model="contractForm.cost" placeholder="请输入合同金额">
                  <template #prepend>¥</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="到账金额" prop="cost2">
                <el-input v-model="contractForm.cost2" placeholder="请输入到账金额">
                  <template #prepend>¥</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="后期服务费">
                <el-input
                  v-model="contractForm.cost3"
                  placeholder="请输入后期服务费"
                  type="textarea"
                  :rows="2"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同开始时间" prop="start_time">
                <el-date-picker
                  v-model="contractForm.start_time"
                  type="date"
                  placeholder="选择合同开始时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="合同结束时间" prop="end_time">
                <el-date-picker
                  v-model="contractForm.end_time"
                  type="date"
                  placeholder="选择合同结束时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 签订信息 -->
      <div class="form-section">
        <h3 class="form-section-title">签订信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同签订人" prop="sign_uid">
                <el-select
                  v-model="contractForm.sign_uid"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索用户"
                  :remote-method="remoteSearchUsers"
                  :loading="userLoading"
                  @change="handleUserChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in userOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                    <span>{{ item.name }}</span>
                    <span
                      v-if="item.department"
                      style="float: right; color: #8492a6; font-size: 13px"
                    >
                      {{ item.department }}
                    </span>
                  </el-option>
                </el-select>
                <input type="hidden" v-model="contractForm.sign_name" />
                <!-- 隐藏字段：合同所属部门 -->
                <input type="hidden" v-model="contractForm.did" />
                <input type="hidden" v-model="contractForm.sign_department" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <!-- 空列，保持布局 -->
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同签订日期" prop="sign_time">
                <el-date-picker
                  v-model="contractForm.sign_time"
                  type="date"
                  placeholder="选择合同签订日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <!-- 空列，保持布局 -->
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 附件信息 -->
      <div class="form-section">
        <h3 class="form-section-title">附件信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="合同附件">
                <el-upload
                  ref="uploadRef"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :on-remove="handleUploadRemove"
                  :file-list="fileList"
                  :auto-upload="false"
                  multiple
                  :limit="5"
                >
                  <el-button type="primary">选择文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">最多可上传5个文件，支持PDF、Word、Excel等格式</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 其他信息 -->
      <div class="form-section">
        <h3 class="form-section-title">其他信息</h3>
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="合同备注">
                <el-input
                  v-model="contractForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入合同备注"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>

    <!-- 客户选择对话框 -->
    <el-dialog
      v-model="customerDialogVisible"
      title="选择客户"
      width="800px"
      destroy-on-close
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="selector-container">
        <!-- 搜索区域 -->
        <div class="search-box">
          <el-input
            v-model="customerSearchKeywords"
            placeholder="请输入客户名称或联系方式搜索"
            clearable
            class="search-input"
            @keyup.enter="getCustomerList"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="getCustomerList">搜索</el-button>
          <el-button type="success" @click="openAddCustomerDrawer" style="margin-left: 10px">
            新增客户
          </el-button>
        </div>

        <!-- 客户列表 -->
        <div class="table-container">
          <el-table
            :data="customerList || []"
            border
            height="400px"
            highlight-current-row
            row-key="id"
            empty-text="暂无数据"
            @row-click="handleCustomerRowClick"
          >
            <el-table-column type="index" width="60" label="序号" align="center" />
            <el-table-column prop="name" label="客户名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="contact_name" label="联系人" min-width="120" align="center" />
            <el-table-column
              prop="contact_mobile"
              label="联系电话"
              min-width="140"
              align="center"
            />
            <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-box">
          <el-pagination
            background
            v-model:current-page="customerQueryForm.page"
            v-model:page-size="customerQueryForm.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="customerTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleCustomerSizeChange"
            @current-change="handleCustomerCurrentChange"
          ></el-pagination>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="customerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCustomerSelect" :disabled="!selectedCustomer">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增客户抽屉 - 使用统一的CustomerDrawer组件 -->
    <CustomerDrawer
      v-model="addCustomerDrawerVisible"
      :customer-id="''"
      mode="add"
      size="80%"
      @success="handleAddCustomerSuccess"
    />

    <!-- 部门选择对话框 -->
    <el-dialog
      v-model="departmentDialogVisible"
      title="选择部门"
      width="600px"
      destroy-on-close
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="selector-container">
        <!-- 部门列表 -->
        <div class="table-container">
          <el-table
            :data="departmentList || []"
            border
            height="400px"
            highlight-current-row
            row-key="id"
            empty-text="暂无数据"
            @row-click="handleDepartmentRowClick"
          >
            <el-table-column type="index" width="60" label="序号" align="center" />
            <el-table-column prop="title" label="部门名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="leader" label="部门负责人" min-width="120" align="center" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="departmentDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmDepartmentSelect"
            :disabled="!selectedDepartment"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Search, Plus, Close } from '@element-plus/icons-vue'
  import { contractApi } from '@/api/contract'
  import { cate } from '@/api/home/cate'
  import { customerApi } from '@/api/customer'
  import { userApi } from '@/api/user'
  import CustomerDrawer from '@/components/business/customer/CustomerDrawer.vue'

  // 定义emit事件
  const emit = defineEmits(['submit', 'cancel'])

  // 路由
  import { useRouter } from 'vue-router'
  const router = useRouter()

  // 表单引用
  const formRef = ref()

  // 激活的Tab
  const activeTab = ref('basic')

  // 合同表单数据
  // 定义合同表单类型
  interface ContractForm {
    name: string
    code: string
    subject_id: string
    cate_id: string
    customer: string
    customer_id: number | undefined
    contact_name: string
    contact_mobile: string
    cost: string
    cost2: string
    cost3: string
    start_time: string
    end_time: string
    sign_name: string
    sign_uid: string
    sign_department: string
    did: string
    sign_time: string
    remark: string
    types: number
    file_ids: string
  }

  const contractForm = reactive<ContractForm>({
    name: '',
    code: '',
    subject_id: '',
    cate_id: '',
    customer: '',
    customer_id: undefined, // 允许number或undefined类型
    contact_name: '',
    contact_mobile: '',
    cost: '',
    cost2: '',
    cost3: '',
    start_time: '',
    end_time: '',
    sign_name: '',
    sign_uid: '',
    sign_department: '',
    did: '',
    sign_time: '',
    remark: '',
    types: 1, // 添加合同类型字段，默认为1（销售合同）
    file_ids: '', // 添加文件ID字段
  })

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
    subject_id: [{ required: true, message: '请选择签约主体公司', trigger: 'change' }],
    cate_id: [{ required: true, message: '请选择合同类别', trigger: 'change' }],
    customer: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    contact_name: [{ required: true, message: '请输入客户代表姓名', trigger: 'blur' }],
    cost: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
    cost2: [{ required: true, message: '请输入到账金额', trigger: 'blur' }],
    start_time: [{ required: true, message: '请选择合同开始时间', trigger: 'change' }],
    end_time: [{ required: true, message: '请选择合同结束时间', trigger: 'change' }],
    sign_uid: [{ required: true, message: '请选择合同签订人', trigger: 'change' }],
    // did 字段已设为隐藏，不再需要验证
    // did: [
    //   { required: true, message: '请选择合同所属部门', trigger: 'change' }
    // ],
    sign_time: [{ required: true, message: '请选择合同签订日期', trigger: 'change' }],
  }

  // 企业列表
  const enterpriseList = ref<any[]>([])

  // 合同分类列表
  const contractCategories = ref<any[]>([])

  // 客户列表相关
  const customerDialogVisible = ref(false)
  const customerSearchKeywords = ref('')
  const customerList = ref<any[]>([])
  const customerTotal = ref(0)
  const customerQueryForm = reactive({
    page: 1,
    limit: 10,
  })
  const selectedCustomer = ref<any>(null)

  // 新增客户抽屉相关
  const addCustomerDrawerVisible = ref(false)

  // 用户远程搜索相关
  const userOptions = ref<any[]>([])
  const userLoading = ref(false)

  // 远程搜索用户
  const remoteSearchUsers = async (query: string) => {
    if (query === '') {
      userOptions.value = []
      return
    }

    userLoading.value = true
    try {
      // 使用getUserList接口，支持关键词搜索（注意参数是keywords不是keyword）
      const response = await userApi.getUserList({ keywords: query, page: 1, limit: 20 })

      if (response.code === 0 && response.data) {
        // 根据返回数据格式处理
        let users = []
        if (Array.isArray(response.data)) {
          users = response.data
        } else if (response.data.list) {
          users = response.data.list
        } else if ('data' in response.data && Array.isArray(response.data.data)) {
          users = response.data.data
        } else {
          users = Object.values(response.data)
        }

        // 转换为前端需要的格式
        userOptions.value = users.map((user: any) => ({
          id: user.id,
          name: user.name || user.username || user.real_name,
          department: user.department_name || user.dept_name || user.department || '',
          did: user.department_id || user.dept_id || '',
          username: user.username,
        }))
      } else {
        userOptions.value = []
        ElMessage.warning(response.msg || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表错误:', error)
      userOptions.value = []
      ElMessage.error('获取用户列表失败')
    } finally {
      userLoading.value = false
    }
  }

  // 处理用户选择变更
  const handleUserChange = (userId: number) => {
    // 从选项中找到对应的用户
    const selectedUser = userOptions.value.find(item => item.id === userId)

    if (selectedUser) {
      // 设置用户名称
      contractForm.sign_name = selectedUser.name

      // 自动设置合同所属部门（隐藏字段）
      if (selectedUser.did) {
        contractForm.did = selectedUser.did
      }
      if (selectedUser.department) {
        contractForm.sign_department = selectedUser.department
      }

      ElMessage.success('用户选择成功')
    }
  }

  // 部门列表相关
  const departmentDialogVisible = ref(false)
  const departmentList = ref<any[]>([])
  const selectedDepartment = ref<any>(null)

  // 上传相关
  const uploadRef = ref()
  const uploadUrl = ref(import.meta.env.VITE_API_BASE_URL + '/home/files/upload')
  const uploadHeaders = ref({
    Authorization: 'Bearer ' + localStorage.getItem('token'),
  })
  const fileList = ref([])

  // 上传成功处理
  const handleUploadSuccess = (response: any, file: any, fileList: any) => {
    if (response.code === 0 && response.data && response.data.id) {
      // 将上传成功的文件ID添加到fileList中
      const uploadedFile = {
        id: response.data.id,
        name: response.data.name,
        size: response.data.filesize,
        url: response.data.filepath,
      }

      // 更新fileList
      fileList.value = [...fileList.value, uploadedFile]

      // 更新合同表单的file_ids字段
      const fileIds = fileList.value.map((item: any) => item.id).join(',')
      contractForm.file_ids = fileIds

      ElMessage.success('文件上传成功')
    } else {
      ElMessage.error(response.msg || '文件上传失败')
    }
  }

  // 上传失败处理
  const handleUploadError = (error: any, file: any, fileList: any) => {
    ElMessage.error('文件上传失败')
  }

  // 文件移除处理
  const handleUploadRemove = (file: any, fileList: any) => {
    // 更新fileList
    fileList.value = fileList

    // 更新合同表单的file_ids字段
    const fileIds = fileList.value.map((item: any) => item.id).join(',')
    contractForm.file_ids = fileIds
  }

  // 返回上一页
  const goBack = () => {
    router.back()
  }

  // 选择客户
  const selectCustomer = () => {
    getCustomerList()
    customerDialogVisible.value = true
  }

  // 打开新增客户抽屉
  const openAddCustomerDrawer = () => {
    customerDialogVisible.value = false // 关闭客户选择对话框
    addCustomerDrawerVisible.value = true // 打开新增客户抽屉
  }

  // 关闭新增客户抽屉
  const closeAddCustomerDrawer = () => {
    addCustomerDrawerVisible.value = false
  }

  // 处理新增客户成功
  const handleAddCustomerSuccess = async () => {
    addCustomerDrawerVisible.value = false

    // 获取最新添加的客户（最后一个）
    try {
      // 重新加载客户列表，获取最新数据
      const response = await customerApi.getCustomerList({
        page: 1,
        limit: 1,
        sort: 'create_time desc',
      })
      if (
        response.code === 0 &&
        response.data &&
        response.data.list &&
        response.data.list.length > 0
      ) {
        const latestCustomer = response.data.list[0]
        // 自动回填客户信息到合同表单
        contractForm.customer = latestCustomer.name
        contractForm.customer_id = latestCustomer.id
        if (latestCustomer.contact_name) {
          contractForm.contact_name = latestCustomer.contact_name
        }
        if (latestCustomer.contact_mobile) {
          contractForm.contact_mobile = latestCustomer.contact_mobile
        }
        ElMessage.success('新增客户成功，已自动回填到合同表单')
      } else {
        ElMessage.success('新增客户成功')
      }
    } catch (error) {
      console.error('获取最新客户信息失败:', error)
      ElMessage.success('新增客户成功')
    }
  }

  // 选择部门
  const selectDepartment = () => {
    getDepartmentList()
    departmentDialogVisible.value = true
  }

  // 处理客户选择
  const handleCustomerSelect = (row: any) => {
    selectedCustomer.value = row
  }

  // 行点击处理客户选择
  const handleCustomerRowClick = (row: any) => {
    selectedCustomer.value = row
  }

  // 确认客户选择
  const confirmCustomerSelect = () => {
    if (selectedCustomer.value) {
      contractForm.customer = selectedCustomer.value.name
      contractForm.customer_id = selectedCustomer.value.id
      // 如果客户有联系人信息，自动填充
      if (selectedCustomer.value.contact_name) {
        contractForm.contact_name = selectedCustomer.value.contact_name
      }
      if (selectedCustomer.value.contact_mobile) {
        contractForm.contact_mobile = selectedCustomer.value.contact_mobile
      }
      customerDialogVisible.value = false
      ElMessage.success('客户选择成功')
    } else {
      ElMessage.warning('请先选择客户')
    }
  }

  // 处理部门选择
  const handleDepartmentSelect = (row: any) => {
    selectedDepartment.value = row
  }

  // 行点击处理部门选择
  const handleDepartmentRowClick = (row: any) => {
    selectedDepartment.value = row
  }

  // 确认部门选择
  const confirmDepartmentSelect = () => {
    if (selectedDepartment.value) {
      contractForm.sign_department = selectedDepartment.value.title
      contractForm.did = selectedDepartment.value.id
      departmentDialogVisible.value = false
      ElMessage.success('部门选择成功')
    } else {
      ElMessage.warning('请先选择部门')
    }
  }

  // 处理客户分页大小变化
  const handleCustomerSizeChange = (val: number) => {
    customerQueryForm.limit = val
    getCustomerList()
  }

  // 处理客户当前页变化
  const handleCustomerCurrentChange = (val: number) => {
    customerQueryForm.page = val
    getCustomerList()
  }

  // 提交表单
  const submitForm = () => {
    if (!formRef.value) return

    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          // 处理时间字段，确保传递正确格式给后端
          const submitData: any = { ...contractForm }

          // 确保时间字段是字符串格式 YYYY-MM-DD
          if (submitData.start_time && typeof submitData.start_time !== 'string') {
            submitData.start_time = new Date(submitData.start_time).toISOString().split('T')[0]
          }
          if (submitData.end_time && typeof submitData.end_time !== 'string') {
            submitData.end_time = new Date(submitData.end_time).toISOString().split('T')[0]
          }
          if (submitData.sign_time && typeof submitData.sign_time !== 'string') {
            submitData.sign_time = new Date(submitData.sign_time).toISOString().split('T')[0]
          }

          // 调用新后端接口保存合同信息
          const response: any = await contractApi.addContract(submitData)

          if (response.code === 0) {
            ElMessage.success('新增合同成功')
            // 触发父组件的submit事件，然后关闭抽屉
            emit('submit')
          } else {
            ElMessage.error(response.msg || '新增合同失败')
          }
        } catch (error) {
          ElMessage.error('新增合同失败')
        }
      }
    })
  }

  // 重置表单
  const resetForm = () => {
    // 重置表单数据到初始状态
    if (formRef.value) {
      formRef.value.resetFields()
    }

    // 手动重置其他可能不在表单验证规则内的字段
    contractForm.sign_name = ''
    contractForm.sign_department = ''
    contractForm.remark = ''
    contractForm.cost3 = ''
    contractForm.file_ids = '' // 重置文件ID字段

    // 重置选择器相关数据
    userOptions.value = []
    selectedCustomer.value = null
    selectedDepartment.value = null

    // 重置文件列表
    fileList.value = []

    // 重置上传组件
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
  }

  // 获取企业列表
  const getEnterpriseList = async () => {
    try {
      // 调用获取企业列表的接口
      const response: any = await cate.getEnterpriseList()

      if (response.code === 0) {
        if (Array.isArray(response.data)) {
          enterpriseList.value = response.data
        } else if (
          response.data &&
          typeof response.data === 'object' &&
          (response.data as any).list
        ) {
          enterpriseList.value = (response.data as any).list
        } else if (response.data && typeof response.data === 'object') {
          enterpriseList.value = Object.values(response.data)
        } else {
          enterpriseList.value = []
        }
      } else {
        ElMessage.error(response.msg || '获取企业列表失败')
      }
    } catch (error) {
      console.error('获取企业列表失败:', error)
      ElMessage.error('获取企业列表失败')
      enterpriseList.value = []
    }
  }

  // 获取合同分类列表
  const getContractCategories = async () => {
    try {
      const response: any = await contractApi.getContractCategories()

      if (response.code === 0) {
        if (Array.isArray(response.data)) {
          contractCategories.value = response.data
        } else if (
          response.data &&
          typeof response.data === 'object' &&
          (response.data as any).list
        ) {
          contractCategories.value = (response.data as any).list
        } else if (response.data && typeof response.data === 'object') {
          contractCategories.value = Object.values(response.data)
        } else {
          contractCategories.value = []
        }
      } else {
        ElMessage.error(response.msg || '获取合同分类失败')
      }
    } catch (error) {
      console.error('获取合同分类失败:', error)
      ElMessage.error('获取合同分类失败')
      contractCategories.value = []
    }
  }

  // 获取客户列表
  const getCustomerList = async () => {
    try {
      const params = {
        ...customerQueryForm,
        keywords: customerSearchKeywords.value,
      }
      const response: any = await customerApi.getCustomerList(params)

      if (response.code === 0) {
        // 根据API响应结构判断数据格式
        if (Array.isArray(response.data)) {
          // 如果数据是数组
          customerList.value = response.data
          customerTotal.value = response.data.length
        } else if (response.data && typeof response.data === 'object') {
          // 标准分页格式：{list: [...], total: 559, page: 1, limit: 10, pages: 56}
          if (response.data.list !== undefined) {
            customerList.value = response.data.list
            customerTotal.value = response.data.total || 0
          } else if (response.data.data !== undefined) {
            // 兼容格式：{data: [...], total: 559}
            customerList.value = Array.isArray(response.data.data) ? response.data.data : []
            customerTotal.value = response.data.total || 0
          } else {
            // 其他对象格式，转换为数组
            customerList.value = Object.values(response.data)
            customerTotal.value = response.data.total || response.data.count || 0
          }
        } else {
          // 如果数据为空或其他格式
          customerList.value = []
          customerTotal.value = 0
        }
      } else {
        ElMessage.error(response.msg || '获取客户列表失败')
      }
    } catch (error) {
      console.error('获取客户列表错误:', error)
      ElMessage.error('获取客户列表失败')
      customerList.value = []
      customerTotal.value = 0
    }
  }

  // 获取部门列表
  const getDepartmentList = async () => {
    try {
      const response: any = await userApi.getDepartmentList()

      if (response.code === 0) {
        // 根据API响应结构判断数据格式
        if (Array.isArray(response.data)) {
          // 如果数据是数组
          departmentList.value = response.data
        } else if (
          response.data &&
          typeof response.data === 'object' &&
          (response.data as any).list
        ) {
          // 如果数据是对象并有list属性
          departmentList.value = (response.data as any).list
        } else if (response.data && typeof response.data === 'object') {
          // 如果数据是对象但没有list属性，转换为数组
          departmentList.value = Object.values(response.data)
        } else {
          // 如果数据为空或其他格式
          departmentList.value = []
        }
      } else {
        ElMessage.error(response.msg || '获取部门列表失败')
      }
    } catch (error) {
      console.error('获取部门列表错误:', error)
      ElMessage.error('获取部门列表失败')
      departmentList.value = []
    }
  }

  // 页面加载时初始化数据
  onMounted(() => {
    getEnterpriseList()
    getContractCategories()
  })

  // 暴露方法给父组件
  defineExpose({
    submitForm,
    resetForm,
  })
</script>

<style scoped>
  /* 选择器容器 */
  .selector-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .search-box {
    display: flex;
    margin-bottom: 15px;
    gap: 10px;
  }

  /* 修改搜索输入框宽度，不再占据所有剩余空间 */
  .search-input {
    width: 300px; /* 设置一个合适的固定宽度 */
  }

  .table-container {
    flex: 1;
    margin-bottom: 15px;
  }

  .pagination-box {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }

  /* 对话框页脚 */
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 12px;
  }
</style>
